package cn.bugstack.domain.strategy.service.rule.mytree.impl;

import cn.bugstack.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import cn.bugstack.domain.strategy.repository.IStrategyRepository;
import cn.bugstack.domain.strategy.service.armory.IStrategyDispatch;
import cn.bugstack.domain.strategy.service.rule.tree.ILogicTreeNode;
import cn.bugstack.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;

import javax.annotation.Resource;

/**
 * TODO
 *
 * @Description 扣减库存节点
 * @Author Lx
 * @Date 2024/8/5 23:23
 **/
public class decrCountNode implements ILogicTreeNode {

    @Resource
    IStrategyDispatch strategyDispatch;

    @Resource
    IStrategyRepository strategyRepository;

    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue) {
        //1.缓存扣减库存(缓存用sentx锁每个库存数量，来保证高并发，做到锁的粒度最小
        strategyRepository.DecrStockFromCache();//用strategyId,awardId,来作为cachekey

        //2.消息队列传发送数据库扣的库存的信息
        strategyDispatch.sendDeductStockMsg(strategyId, awardId);

        //3.扣减成功
        if(true)
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                .strategyAwardVO(null)
                .build();


        //4.扣减失败，判断是扣到了同一个库存，还是空了。固定顺序(次数锁校验,
        //4.1.空了直接清空队列，和库存置为0，再take_over


        //4.2.如果是因为并发扣减了同一个库存，那就直接take_over




        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                .strategyAwardVO(null)
                .build();
    }
}
